package com.das.cloudmetro.ssoserver.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import com.liy.framework.common.utils.*;

@Configuration
public class FeignInterceptorService implements RequestInterceptor
{
    private Logger log;

    @Value("${dascloud.authrization.enabled: true}")
    private Boolean enabled;
    @Value("${dascloud.authrization.token-header:JwtToken}")
    private String tokenHeader;
    @Value("${dascloud.authrization.auth-key:AuthKey}")
    private String authKeyHeader;
    
    public FeignInterceptorService() {
        this.log = LoggerFactory.getLogger((Class)FeignInterceptorService.class);
    }
    
    public void apply(final RequestTemplate requestTemplate) {
        if (!this.enabled) {
            return;
        }
        this.log.debug("Add authentication key to feign request: " + this.tokenHeader + ":" + this.authKeyHeader);
        this.log.debug(ContextHandler.getJwtToken());
        requestTemplate.header(this.tokenHeader, new String[] { ContextHandler.getJwtToken() });
        requestTemplate.header(this.authKeyHeader, new String[] { ContextHandler.getAuthKey() });
    }
    
    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private Map<String, String> getHeaders(final HttpServletRequest request) {
        final Map<String, String> map = new LinkedHashMap<String, String>();
        final Enumeration<String> enumeration = (Enumeration<String>)request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            final String key = enumeration.nextElement();
            final String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
